<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/7
 * Time: 9:56
 */

namespace app\index\controller;
header("Content-type: text/html; charset=utf-8");

use app\common\controller\PayBase;
use think\Db;
use app\index\model\ChongzhiList;

class Paylfzf extends PayBase{
    private $merchNo;
    private $key;
    private $pay_url;
    private $back_url;
    private $view_url;
    private $version;

    public function __construct(){
        parent::__construct();
        $this->merchNo = 'LFP201808250000';
        $this->key = '7D7E768BB4CB7EBCE6E3B067A6351342';
        $this->pay_url = 'http://47.94.6.240:9003/api/pay';
        $this->back_url = 'http://www.my67.cc/index/Paylfzf/callBack';
        $this->view_url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Paylfzf/viewUrl';
        $this->version = 'V3.6.0.0';

    }
    public function initPay($username='',$pay_type='',$amount=-1,$from=0){
        //接收数据
        $user = cookie('username','');
        $password = cookie('password','');
        $username =  empty($username) ? input('post.username','') : $username;
        $pay_type = empty($pay_type) ? input('post.pay_type','') : $pay_type;
        $amount = -1==$amount ? input('post.amount',0) : $amount;
        $ctime = time();

        if($pay_type=='null' || $pay_type=='') return packJson('',$pay_type.'请选择支付方式',500);
        $pay_method = Db::name('pay_type_list')
            ->alias("a")
            ->join('__PAY_METHOD__ b','a.method_id=b.id','LEFT')
            ->where(['a.method'=>16,'a.type_value'=>$pay_type])
            ->field('a.type_name,b.name,b.id,b.method,b.money')->find();

        $remark = $pay_method['type_name'].'-'.$pay_method['name'];

        //验证用户信息
        if( 0==$from ){
            if(!$user || !$username || ($user!=$username)) return packJson('','用户身份验证失败',500);
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username,'password'=>$password])->find();
        }else{
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username])->find();
        }
        if(!$user_info) return packJson('','用户身份验证失败',500);
        if($user_info['swzh'] == 1) return packJson('','试玩账号无法充值',500);
        if($user_info['nbzh'] == 1) return packJson('','内部账号不支持线上充值',500);

        //充值防骚扰是否开启，并进行处理
        $harassment = Db::name('xt_czfsr')->find();
        if($harassment['open'] > 0) {
            $nowys = $ctime - $harassment['time_xs'] * 60;
            $old_czjl = Db::name('chongzhi_list')->where('username',$username)->where('cztime','>',$nowys)->find();
            if($old_czjl['id'] > 0) {
//                return packJson('',"系统充值防骚扰已开启，{$harassment['time_xs']}分钟内只能充值1次！",500);
            }
        }
        //生成订单号
        $order_sn = 'LFF' . str_pad($user_info['id'],5,'0',STR_PAD_LEFT) . $ctime . rand(111,999);
        //组装数据
        if( 1==$from ) $this->view_url.="Third";
        $data = array();

        $data['orderNo'] = $order_sn;
        $data['randomNo'] = (string) rand(1000,9999);
        $data['merchNo'] = $this->merchNo;
        $data['netwayType'] = $pay_type;
        $data['amount'] = strval( floatval($amount) * 100 );	// 单位:分
        $data['goodsName'] = '隆发线上支付';
        $data['notifyUrl'] = $this->back_url;
        $data['notifyViewUrl'] = $this->view_url;

        $data['sign'] = create_sign($data,$this->key);
        $json = json_encode_ex($data);
        $Rsa = new Rsa();
        $dataStr = $Rsa->encode_pay($json);
        $param = 'data=' . urlencode($dataStr) . '&merchNo=' . $this->merchNo . '&version=' . $this->version;

        $result = wx_post($this->pay_url,$param);
        $rows = json_to_array($result,$this->key);

        if( '00' === $rows['stateCode'] ){
            $u = Db::name('username')->where('username',$username)->value('je');
            $model = new ChongzhiList();
            if($model->setTransRechargeInfo($order_sn,$amount,$username,0,0,1,$remark,$ctime,'隆发线上支付','系统自动',get_ip(),0,$pay_type,0,0,0,0,$user_info['us_class'],'',0,0,$u)){
                //跳转支付页
                return packJson($rows['qrcodeUrl'],'',200);
            }else{
                return packJson('',"订单生产错误",500);
            }
        }else{
            return packJson('',$rows['msg'],500);
        }
    }
    public function callBack(){
        file_put_contents('lf_back.txt',var_export(input(),true),FILE_APPEND);
    }
    public function viewUrl(){
        file_put_contents('lf_view.txt',var_export(input(),true),FILE_APPEND);
    }
    public function viewUrlThird(){
        file_put_contents('lf_view_three.txt',var_export(input(),true),FILE_APPEND);
    }
}

class Rsa{
    private $pay_public_key;
    private $remit_public_key;
    private $private_key;

    public function __construct($key = null){
        $data['private_key'] = 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKIE9OWSfOqoxKZTsOmaOXV0KdD44Bhz0JFxv/NaD36xu1Jfeg4MMb6yqPqckmSFE/+BFU+doHTC3VXqqWZbo6pfAL8r7P9oIWGoX+EJ1MyP/m92y15UXFdtA+DyyT1Rw24Gn/M46Vhg8RhsZ7a8/w/63LXGBVVUBaa2QBSidyB7AgMBAAECgYEAjlnGhdIwGMjRhsWvgX+0jkLS3r1bv4A6Nx/3I6v0Qz+LMvOaPK9wIXm9x/s7EEBwcqQKgloe+ZegenVkAv/vCkDI7tC0M4F3+dB06UM3zzvr9iRqnFnjVkbgF/nSkUMgd0wqfSaGDyA7Koq3cliWGNRSsz69Tjrp9lxfW/XuamkCQQDjQaphUX685dRA4G4jdZW0LxDIUelhD74vExp9GwzAE4BVnT3SdsdELia1osgujZOheoewpyGtw+xmgIs73hfHAkEAtoL6jaP9KiyxX82eOqqEYhftROTgInee9oCB+/CpAFRRj8PXjbnpdKx0DiPuiv3GTPIpqq5zWXdTkuw2Urx5rQJALT+w5gms+32jgnttUqAh+6t3Yvt0RYA19PePyaMuKbx4TBOv8Iz35ipuSLItu58y6u8Tv2e3u/qLwmkL0BLLlwJBALOh0GbOC6OR33Yyk1ScdbVyZUYUmoFyCNQHAWhtoni/hJMiJyrH233JKmSseuD0C1O6WMYz8zYQGwKVWJYwCPUCQAK2NQ3vJppXA3NydlRqsUUDMrjkymO1n9hcYErfxC9ThDk+/uV6tURZawODR0QvroZjcwDA3ilTPKLcDyB74No=';
        $data['pay_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHuFeMRs5k7DZwi6QPYlPVFRsGv7CytIMyK2XvdXH0YRCYM3OZhXH6l3TCrOrGtJax01N0jyVsqxaaiYqfR06IarJGWYqTY9IXI6mvP1Fd33YNmByw0Mm0VsvGoChKlzMI8GV/Wt0lb3oGdBPhvCVuxpN59QjeqekHmgUzwr9OIwIDAQAB';
        $data['remit_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMX7BiAroLRgq7U4zVmIjZ0OS7pMETJ3chAeN3LPK2SIcVhtlog/NtZTUgqF7eV0tb5JqIO9SjiFxY9rAHoCQhocTEi3KWcY7xbOlbqRB8sfLPJbFADCRmXaG8AozaURsWU2yut7WF5sWwHYZsJ0/wWea+2FsEZ1vktM8/fS4VRQIDAQAB';
        $this->private_key = "-----BEGIN RSA PRIVATE KEY-----\r\n";
        foreach (str_split($data['private_key'],64) as $str){
            $this->private_key = $this->private_key . $str . "\r\n";
        }
        $this->private_key = $this->private_key . "-----END RSA PRIVATE KEY-----";

        $this->pay_public_key = "-----BEGIN PUBLIC KEY-----\r\n";
        foreach (str_split($data['pay_public_key'],64) as $str){
            $this->pay_public_key = $this->pay_public_key . $str . "\r\n";
        }
        $this->pay_public_key = $this->pay_public_key . "-----END PUBLIC KEY-----";



        $this->remit_public_key = "-----BEGIN PUBLIC KEY-----\r\n";
        foreach (str_split($data['remit_public_key'],64) as $str){
            $this->remit_public_key = $this->remit_public_key . $str . "\r\n";
        }
        $this->remit_public_key = $this->remit_public_key . "-----END PUBLIC KEY-----";
    }

    public function encode_pay($data){#加密
        $pu_key = openssl_pkey_get_public($this->pay_public_key);
        if ($pu_key == false){
            echo "打开密钥出错";
            die;
        }
        $encryptData = '';
        $crypto = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_public_encrypt($chunk, $encryptData, $pu_key);
            $crypto = $crypto . $encryptData;
        }

        $crypto = base64_encode($crypto);
        return $crypto;

    }


    public function encode_remit($data){#加密
        $pu_key = openssl_pkey_get_public($this->remit_public_key);
        if ($pu_key == false){
            echo "打开密钥出错";
            die;
        }
        $encryptData = '';
        $crypto = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_public_encrypt($chunk, $encryptData, $pu_key);
            $crypto = $crypto . $encryptData;
        }

        $crypto = base64_encode($crypto);
        return $crypto;

    }



    public function decode($data){
        $pr_key = openssl_get_privatekey($this->private_key);
        if ($pr_key == false){
            echo "打开密钥出错";
            die;
        }
        $data = base64_decode($data);
        $crypto = '';
        foreach (str_split($data, 128) as $chunk) {
            openssl_private_decrypt($chunk, $decryptData, $pr_key);
            $crypto .= $decryptData;
        }
        return $crypto;
    }


}


function p($array){
    $str = '<pre>' . print_r($array,true) . '</pre>';
    echo $str;
}
function ps($array){
    $str =  print_r($array,true);
    return $str;
}

function wx_post($url,$data){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    if (curl_errno($ch)) {
        return curl_error($ch);
    }
    return $tmpInfo;

}

function json_encode_ex($value){
    if (version_compare(PHP_VERSION,'5.4.0','<')){
        $str = json_encode($value);
        $str = preg_replace_callback("#\\\u([0-9a-f]{4})#i","replace_unicode_escape_sequence",$str);
        $str = stripslashes($str);
        return $str;
    }else{
        return json_encode($value,320);
    }
}

function json_decode_ex($value){
    return json_decode($value,true);
}

function replace_unicode_escape_sequence($match) {
    return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}
function log_write($log){
    $file = date('Y-m-d') . '.log';
    $str = date('H:i:s') . " " . $log . "\r\n";
    file_put_contents($file,$str,FILE_APPEND);
}

function create_sign($data,$key){
    ksort($data);
    $sign = strtoupper(md5(json_encode_ex($data) . $key));
    return $sign;
}

function json_to_array($json,$key){
    $array = json_decode_ex($json);
    if ($array['stateCode'] == '00'){
        $sign_string = $array['sign'];
        ksort($array);
        $sign_array = array();
        foreach ($array as $k => $v) {
            if ($k !== 'sign'){
                $sign_array[$k] = $v;
            }
        }

        $md5 =  strtoupper(md5(json_encode_ex($sign_array) . $key));
        if ($md5 == $sign_string){
            return $sign_array;
        }else{
            $result = array();
            $result['stateCode'] = '99';
            $result['msg'] = '返回签名验证失败';
            return $result;
        }



    }else{
        $result = array();
        $result['stateCode'] = $array['stateCode'];
        $result['msg'] = $array['msg'];
        return $result;
    }

}


function callback_to_array($json,$key){
    $array = json_decode_ex($json);
    $sign_string = $array['sign'];
    ksort($array);
    $sign_array = array();
    foreach ($array as $k => $v) {
        if ($k !== 'sign'){
            $sign_array[$k] = $v;
        }
    }
    $md5 =  strtoupper(md5(json_encode_ex($sign_array) . $key));
    if ($md5 == $sign_string){
        return $sign_array;
    }else{
        $result = array();
        $result['payStateCode'] = '99';
        $result['msg'] = '返回签名验证失败';
        return $result;
    }

}